import {createRouter, createWebHistory} from 'vue-router'
import {useLoginStatus} from '@/hooks/loginStatusHooks/loginStatus.ts';

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'index',
      component: () => import('@/pages/index/index.vue'),
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/pages/login/login.vue'),
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('@/pages/register/register.vue'),
    }
  ],
})

router.beforeEach((to, from, next) => {
  //验证登录
  if (to.meta.hasOwnProperty('requiresAuth') && to.meta.requiresAuth) {
    const loginStatus = useLoginStatus();
    if (!loginStatus.status) {
      let redirect = encodeURIComponent(to.fullPath)
      return next({path: '/login', query: {redirect: redirect}});
    }
  }

  next();
})

export default router
